<script lang="ts" setup>
import type { ClassifyType } from '@/type/type'
import { type ClassifyLabelVO } from '@/request/api/classify'
import { useTemporaryStore } from '@/stores/temporary'
import type { LabelVO } from '@/request/api/label'

const temporaryStore = useTemporaryStore()
const classifyLabelsList = ref<ClassifyLabelVO[]>([])
const labelList = computed(() => {
  let labels: LabelVO[] = []
  if (temporaryStore.form.classifyId && classifyLabelsList.value.length > 0) {
    labels = temporaryStore.getLabelList(temporaryStore.form.classifyId)
    temporaryStore.form.labelId = labels[0].id
  }
  return labels
})

const rules = {
  classifyId: [{ required: true, message: '类别不能为空', trigger: 'blur' }],
  labelId: [{ required: true, message: '标签不能为空', trigger: 'blur' }]
}

const { type, showClass, showLabel, required } = defineProps({
  type: {
    type: Number as unknown as PropType<ClassifyType>,
    required: true
  },
  showClass: {
    type: Boolean,
    default: true
  },
  showLabel: {
    type: Boolean,
    default: true
  },
  required: {
    type: Boolean,
    default: true
  }
})

onMounted(() => {
  temporaryStore.getClassifyList(type).then((res: ClassifyLabelVO[]) => {
    classifyLabelsList.value = res
    // 初始化表单数据
    if (classifyLabelsList.value.length > 0 && required) {
      temporaryStore.form.classifyId = classifyLabelsList.value[0].id
      if (classifyLabelsList.value[0].labels.length > 0) {
        temporaryStore.form.labelId = classifyLabelsList.value[0].labels[0].id
      }
    }
  })
})
</script>

<template>
  <div class="flex flex-wrap">
    <el-form :rules="rules" class="flex flex-row flex-wrap">
      <el-form-item v-if="showClass" class="w-52" label="类别" prop="classifyId">
        <el-select v-model="temporaryStore.form.classifyId">
          <el-option v-if="!required" key="-1" :value="-1" label="无" />
          <el-option v-for="i in classifyLabelsList" :key="i.name" :label="i.name" :value="i.id" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="showLabel" class="w-52" label="标签" prop="labelId">
        <el-select v-model="temporaryStore.form.labelId">
          <el-option v-if="!required" key="-1" :value="-1" label="无" />
          <el-option v-for="i in labelList" :key="i.name" :label="i.name" :value="i.id" />
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped></style>
